package com.css.zfzx.sjcj.modules.qhseismicfortification.repository.impl;

import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.org.dept.repository.entity.DeptEntity;
import com.css.bpm.platform.org.division.repository.DivisionRepository;
import com.css.bpm.platform.org.division.repository.entity.DivisionEntity;
import com.css.bpm.platform.org.role.repository.entity.RoleEntity;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.zfzx.sjcj.common.utils.ServerUtil;
import com.css.zfzx.sjcj.modules.qhseismicfortification.repository.QhSeismicFortificationNativeRepository;
import com.css.zfzx.sjcj.modules.qhseismicfortification.repository.entity.QhSeismicFortificationEntity;
import com.css.zfzx.sjcj.modules.qhseismicfortification.viewobjects.QhSeismicFortificationQueryParams;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
/**
 * @author tao
 * @date 2020-11-17
 */
@Repository
@PropertySource("classpath:platform-config.yml")
public class QhSeismicFortificationNativeRepositoryImpl implements QhSeismicFortificationNativeRepository {
    @PersistenceContext
    private EntityManager em;

    @Value("${role.superCode}")
    private String superCode;
    @Value("${role.provinceCode}")
    private String provinceCode;
    @Value("${role.cityCode}")
    private String cityCode;
    @Value("${role.areaCode}")
    private String areaCode;
    @Autowired
    private DivisionRepository divisionRepository;

    private static final Logger log = LoggerFactory.getLogger(QhSeismicFortificationNativeRepositoryImpl.class);

    @Override
    public Page<QhSeismicFortificationEntity> queryQhSeismicFortifications(QhSeismicFortificationQueryParams queryParams, int curPage, int pageSize) {
        if(PlatformObjectUtils.isEmpty(queryParams.getIsValid())) {
            if("".equals(queryParams.getDrillCodes())) {
                queryParams.setIsValid("-9527");
            } else {
                queryParams.setIsValid("1");
            }
        }
        StringBuilder sql = new StringBuilder("select * from qh_seismic_fortification");
        StringBuilder whereSql = new StringBuilder(" where 1=1");
        if(!PlatformObjectUtils.isEmpty(queryParams.getProvince())) {
            whereSql.append(" and province = :province");
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getCity())) {
            whereSql.append(" and city = :city");
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getArea())) {
            whereSql.append(" and area = :area");
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getTown())) {
            whereSql.append(" and town like :town");
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getProjectName())) {
            whereSql.append(" and project_name like :projectName");
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getDrillCode())) {
            whereSql.append(" and drill_code like :drillCode");
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getQualityinspectionResult())) {
            whereSql.append(" and qualityinspection_result = :qualityinspectionResult");
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getQualityinspectionStatus())) {
            whereSql.append(" and qualityinspection_status = :qualityinspectionStatus");
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getReviewStatus())) {
            whereSql.append(" and review_status = :reviewStatus");
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getIsValid())) {
            whereSql.append(" and is_valid = :isValid");
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getDrillCodes())) {
            whereSql.append(" and drill_code in :drillCodes");
        }
        String userId = PlatformSessionUtils.getUserId();
        List<RoleEntity> roles = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
        //是否为超级管理员
        boolean containtRole = ServerUtil.isContaintRole(roles, superCode);
        //是否为省级管理员
        boolean containtRolePro = ServerUtil.isContaintRole(roles, provinceCode);
        //是否为市级管理员
        boolean containtRoleCity = ServerUtil.isContaintRole(roles, cityCode);
        //是否为县级管理员
        boolean containtRoleArea=ServerUtil.isContaintRole(roles,areaCode);
        if(!containtRole){
            if (!containtRolePro && !containtRoleCity && !containtRoleArea) {
                whereSql.append(" and creat_user =:userId");
            }
            if(containtRolePro){
                whereSql.append(" and province =:province");
            }
            if(containtRoleCity){
                whereSql.append(" and city =:city");
            }
            if(containtRoleArea){
                whereSql.append(" and area =:area");
            }
        }
        Query query = this.em.createNativeQuery(sql.append(whereSql).toString(), QhSeismicFortificationEntity.class);
        StringBuilder countSql = new StringBuilder("select count(*) from qh_seismic_fortification");
        Query countQuery = this.em.createNativeQuery(countSql.append(whereSql).toString());
        if(!PlatformObjectUtils.isEmpty(queryParams.getProvince())) {
            query.setParameter("province", queryParams.getProvince());
            countQuery.setParameter("province", queryParams.getProvince());
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getCity())) {
            query.setParameter("city", queryParams.getCity());
            countQuery.setParameter("city", queryParams.getCity());
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getArea())) {
            query.setParameter("area", queryParams.getArea());
            countQuery.setParameter("area", queryParams.getArea());
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getTown())) {
            query.setParameter("town", "%" + queryParams.getTown() + "%");
            countQuery.setParameter("town", "%" + queryParams.getTown() + "%");
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getProjectName())) {
            query.setParameter("projectName", "%" + queryParams.getProjectName() + "%");
            countQuery.setParameter("projectName", "%" + queryParams.getProjectName() + "%");
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getDrillCode())) {
            query.setParameter("drillCode", "%" + queryParams.getDrillCode() + "%");
            countQuery.setParameter("drillCode", "%" + queryParams.getDrillCode() + "%");
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getQualityinspectionResult())) {
            query.setParameter("qualityinspectionResult", queryParams.getQualityinspectionResult());
            countQuery.setParameter("qualityinspectionResult", queryParams.getQualityinspectionResult());
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getQualityinspectionStatus())) {
            query.setParameter("qualityinspectionStatus", queryParams.getQualityinspectionStatus());
            countQuery.setParameter("qualityinspectionStatus", queryParams.getQualityinspectionStatus());
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getReviewStatus())) {
            query.setParameter("reviewStatus", queryParams.getReviewStatus());
            countQuery.setParameter("reviewStatus", queryParams.getReviewStatus());
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getIsValid())) {
            query.setParameter("isValid", queryParams.getIsValid());
            countQuery.setParameter("isValid", queryParams.getIsValid());
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getDrillCodes())) {
            String codes = queryParams.getDrillCodes();
            List<String> idList = Arrays.asList(codes.split(","));
            query.setParameter("drillCodes", idList);
            countQuery.setParameter("drillCodes", idList);
        }
        if(!containtRole){
            if (!containtRolePro && !containtRoleCity && !containtRoleArea) {
                query.setParameter("userId",PlatformSessionUtils.getUserId());
                countQuery.setParameter("userId",PlatformSessionUtils.getUserId());
            }
            DeptEntity mainDept = PlatformAPI.getOrgAPI().getUserAPI().getMainDept(userId);
            String divisionId = mainDept.getDivisionId();
            DivisionEntity validDivisionById = divisionRepository.findValidDivisionById(divisionId);
            String divisionName = validDivisionById.getDivisionName();
            if(containtRolePro){
                query.setParameter("province",divisionName);
                countQuery.setParameter("province",divisionName);
            }
            if(containtRoleCity){
                query.setParameter("city",divisionName);
                countQuery.setParameter("city",divisionName);
            }
            if(containtRoleArea){
                query.setParameter("area",divisionName);
                countQuery.setParameter("area",divisionName);
            }
        }
        Pageable pageable = PageRequest.of(curPage - 1, pageSize);
        query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
        query.setMaxResults(pageable.getPageSize());
        List<QhSeismicFortificationEntity> list = query.getResultList();
        BigInteger count = (BigInteger) countQuery.getSingleResult();
        Page<QhSeismicFortificationEntity> qhSeismicFortificationPage = new PageImpl<>(list, pageable, count.longValue());
        return qhSeismicFortificationPage;
    }
}
